package com.polaris.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.core.widget.NestedScrollView
import kotlin.math.abs
import kotlin.math.atan2

/**
 * XNestedScrollView
 *
 * @author Created by 半仙 on 2024/11/15/015 16:51
 */
class XNestedScrollView(context: Context, attrs: AttributeSet? = null) : NestedScrollView(context, attrs) {

    private val mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop

    private var mDownX = 0
    private var mDownY = 0

    private var mDisallowIntercept = false

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mDownX = ev.x.toInt()
                mDownY = ev.y.toInt()

                parent.requestDisallowInterceptTouchEvent(true)
            }

            MotionEvent.ACTION_MOVE -> {
                val moveX = ev.x.toInt()
                val moveY = ev.y.toInt()
                val deltaX = abs(moveX - mDownX)
                val deltaY = abs(moveY - mDownY)

                val angle = atan2(deltaY.toDouble(), deltaX.toDouble()) * (180 / Math.PI)

                if (deltaX > deltaY && deltaX > mTouchSlop && angle <= MIN_ANGLE) {
                    if (mDisallowIntercept) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else {
                        parent.requestDisallowInterceptTouchEvent(false)
                    }

                } else {
                    parent.requestDisallowInterceptTouchEvent(true)
                }
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                mDisallowIntercept = false
                parent.requestDisallowInterceptTouchEvent(true)
            }
        }

        return super.dispatchTouchEvent(ev)
    }

    override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
        this.mDisallowIntercept = disallowIntercept
        super.requestDisallowInterceptTouchEvent(disallowIntercept)
    }

    companion object {

        private const val MIN_ANGLE = 30
    }
}